﻿using Ingr.SP3D.Common.Client.Services;
using Ingr.SP3D.Common.Client;
using Ingr.SP3D.Common.Middle.Services;
using Ingr.SP3D.Common.Middle;
using Microsoft.Win32;
using Newtonsoft.Json;
using NSDataContainer;
using NSSynchronize;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.OleDb;
using System.Windows.Forms;
using static Ingr.SP3D.Common.Client.Services.ErrorHandler;
using static Ingr.SP3D.Common.Client.Services.WorkingSet;
using System.IO;

namespace NSGetData
{
    public class NSSP3DBase
    {
        private void GetConversionUnit()
        {
            UOMManager uOMManager = MiddleServiceProvider.UOMMgr;
            UnitName unitNameDistance = uOMManager.GetDefaultPrimaryUnit(UnitType.Distance);
            UnitName unitNameForce = uOMManager.GetDefaultPrimaryUnit(UnitType.Force);
            UnitName unitNameMoment = uOMManager.GetDefaultPrimaryUnit(UnitType.Moment);
            m_unit_distance = uOMManager.ConvertUnitToUnit(UnitType.Distance, 1.0, unitNameDistance, UnitName.DISTANCE_MILLIMETER);
            m_unit_force = 1e-3;//uOMManager.ConvertUnitToUnit(UnitType.Force, 1.0, unitNameForce, UnitName.FORCE_KILONEWTON);
            m_unit_moment = uOMManager.ConvertUnitToUnit(UnitType.Moment, 1.0, unitNameMoment, UnitName.MOMENT_KILO_NEWTON_METER);
        }
        public void SendHeZaiBollToGAMA()
        {
            GetConversionUnit();
            SelectSet oSelectSet = ClientServiceProvider.SelectSet;
            if (oSelectSet.SelectedObjects.Count == 0)
            {
                CmnException cmnException = new CmnException("没有选择的荷载球");
                ClientServiceProvider.ErrHandler.ReportError(ErrorLevel.Information, "", cmnException);
            }
            else
            {
                try
                {
                    //List<NSSP3DZaiHe> dZaiHes = new List<NSSP3DZaiHe>() { };
                    List<NSSp3dData> dZaiHe2s = new List<NSSp3dData>() { };

                    foreach (BusinessObject businessObject in oSelectSet.SelectedObjects)
                    {
                        NSSp3dData zaiHe2 = null;
                        try
                        {
                            zaiHe2 = GenerateTransStringJson(businessObject);
                        }
                        catch (Exception)
                        {
                            CmnException cmnException = new CmnException("不能生成 NSSp3dData");
                            ClientServiceProvider.ErrHandler.ReportError(ErrorLevel.Information, "", cmnException);
                        }
                        if (zaiHe2 != null)
                        {
                            dZaiHe2s.Add(zaiHe2);
                        }

                    }
                    TransString2GAMA(dZaiHe2s);
                }
                catch (Exception)
                {
                    CmnException cmnException = new CmnException("错误，未发送成功");
                    ClientServiceProvider.ErrHandler.ReportError(ErrorLevel.Critical, "", cmnException);
                }
            }
        }
        private dynamic GetValueFromPropertyValue(PropertyValue propertyValue)
        {
            dynamic value = null;
            if (propertyValue == null) { return value; }
            if (propertyValue.PropertyInfo.PropertyType == SP3DPropType.PTString)
            {
                PropertyValueString propertyValueString = (PropertyValueString)propertyValue;
                if (propertyValueString != null)
                {
                    value = propertyValueString.ToString();
                }
                else
                {
                    value = "";
                }
            }
            else if (propertyValue.PropertyInfo.PropertyType == SP3DPropType.PTDouble)
            {
                PropertyValueDouble propertyValueDouble = (PropertyValueDouble)propertyValue;
                if (!propertyValueDouble.PropValue.HasValue)
                {
                    value = 0;
                }
                else
                {
                    value = propertyValueDouble.PropValue;
                }
            }
            return value;
        }
        private NSSp3dData GenerateTransStringJson(BusinessObject businessObject)
        {
            if (businessObject == null) { return null; }
            Position pointPosition = (Position)businessObject.GetType().GetProperty("Origin").GetValue(businessObject, null);
            NSSp3dData zaiHe2 = new NSSp3dData(businessObject.ToString(),
                pointPosition.X * m_unit_distance, pointPosition.Y * m_unit_distance, pointPosition.Z * m_unit_distance);

            ReadOnlyCollection<PropertyValue> sf = businessObject.GetAllProperties();
            foreach (PropertyValue prop in sf)
            {
                PropertyInformation information = prop.PropertyInfo;
                string str = information.DisplayName;
                if (str == null) { continue; }
                dynamic value = null;
                if (prop.PropertyInfo.PropertyType == SP3DPropType.PTDouble)
                {
                    PropertyValueDouble propertyValueDouble = (PropertyValueDouble)prop;
                    if (!propertyValueDouble.PropValue.HasValue)
                    {
                        value = 0;
                    }
                    else
                    {
                        value = propertyValueDouble.PropValue;
                    }
                }
                if (value == null)
                {
                    continue;
                }
                zaiHe2.AddFields(str, value);
            }
            return zaiHe2;
        }
        private void TransString2GAMA(List<NSSp3dData> dZaiHes)
        {
            List<string> strings = new List<string>
            {
                JsonConvert.SerializeObject(GraphicFormCommand.NSDeadLoadDef),
                JsonConvert.SerializeObject(GraphicFormCommand.NSLiveLoadDef)
            };

            foreach (NSSp3dData zaiHe in dZaiHes)
            {
                string str = JsonConvert.SerializeObject(zaiHe);
                strings.Add(str);
            }
            SendToGAMA(strings);
        }
        private void SendToGAMA(List<string> strings)
        {
            Guid guid = Guid.Parse("{9FC96CD3-320D-4469-BB7D-A762CCA4C47F}");

            GamaCardCreator<string> sendCardToGama = new GamaCardCreator<string>(guid);
            DataContainer<string> names = new DataContainer<string>();
            names.AddDataRange(strings);
            Dictionary<string, int> portList = new Dictionary<string, int>();
            try
            {
                portList = ServerMonitor.GetCurrentPortList("Gama");
            }
            catch (Exception)
            {
                CmnException cmnException = new CmnException("DLL 设置错误 , 获取不到GAMA portList  ");
                ClientServiceProvider.ErrHandler.ReportError(ErrorLevel.Warning, "", cmnException);
                return;
            }

            if (portList.Count != 0)
            {
                sendCardToGama.TransmitData = names;
                sendCardToGama.GamaId = 52231;
                ClientServiceProvider.WorkingSet.Refresh(UpdateQuery.DefaultUpdate);
                try
                {
                    sendCardToGama.Send();
                }
                catch (Exception)
                {
                    CmnException cmnExceptionA = new CmnException("sendCardToGama.Send() 失败");
                    ClientServiceProvider.ErrHandler.ReportError(ErrorLevel.Warning, "", cmnExceptionA);
                }

                CmnException cmnException = new CmnException("已发送到GAMA");
                ClientServiceProvider.ErrHandler.ReportError(ErrorLevel.Information, "", cmnException);

            }
            else
            {
                CmnException cmnException = new CmnException("未检测到运行的GAMA，发送失败");
                ClientServiceProvider.ErrHandler.ReportError(ErrorLevel.Warning, "", cmnException);
            }
        }
        public static void SaveAsJson()
        {
            string filePath = SelectFolder();
            ExportToExcel(filePath);
        }
        private static void ExportToExcel(string filePath)
        {
            try
            {
                string info = JsonConvert.SerializeObject(GraphicFormCommand.NSDeadLoadDef) + "\n" +
           JsonConvert.SerializeObject(GraphicFormCommand.NSLiveLoadDef);

                filePath = Path.Combine(filePath, "nsp.json");
                File.WriteAllText(filePath, info);
                CmnException cmnException = new CmnException("导出成功");
                ClientServiceProvider.ErrHandler.ReportError(ErrorLevel.Information, "", cmnException);
            }
            catch (UnauthorizedAccessException ex)
            {
                CmnException cmnException = new CmnException("文件夹权限不足，请重新选择 或用管理员权限打开");
                ClientServiceProvider.ErrHandler.ReportError(ErrorLevel.Warning, "", cmnException);
            }

        }

        private static string SelectFile ()
        {
            System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
            openFileDialog.Title = "选择一个文件";
            openFileDialog.Filter = "Json文件 (*.json)|*.json";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                // 获取用户选择的文件路径
                string selectedFilePath = openFileDialog.FileName;

                // 输出选择的文件路径
                Console.WriteLine("你选择的文件路径是: " + selectedFilePath);
                return selectedFilePath;
            }
            else
            {
                // 用户取消了文件选择
                Console.WriteLine("文件选择已取消。");
                return string.Empty;
            }
        }

        private static string SelectFolder()
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();

            dialog.Description = "请选择一个文件夹";
            dialog.ShowNewFolderButton = true;
            dialog.RootFolder = Environment.SpecialFolder.Desktop;

            DialogResult result = dialog.ShowDialog();

            if (result == DialogResult.OK && !string.IsNullOrEmpty(dialog.SelectedPath))
            {
                return dialog.SelectedPath;
            }
            else
            {
                return string.Empty;
            }
        }

        public static void ReadFromJson()
        {
            string filePath = SelectFile();
            try
            {
                string info = File.ReadAllText(filePath);
                string[] jsonParts = info.Split(new string[] { "\n" }, StringSplitOptions.None);

                if (jsonParts.Length == 2)
                {
                    GraphicFormCommand.NSDeadLoadDef = JsonConvert.DeserializeObject<NSLoadDef>(jsonParts[0]);
                    GraphicFormCommand.NSLiveLoadDef = JsonConvert.DeserializeObject<NSLoadDef>(jsonParts[1]);

                }
                CmnException cmnException = new CmnException("导入成功");
                ClientServiceProvider.ErrHandler.ReportError(ErrorLevel.Information, "", cmnException);
            }
            catch (Exception)
            {
                CmnException cmnException = new CmnException("导入失败");
                ClientServiceProvider.ErrHandler.ReportError(ErrorLevel.Warning, "", cmnException);
            }
        }
        public static List<NSLoadDef> ReadFromExcel(string filePath)
        {
            var data = new List<NSLoadDef>();
            var connectionString = $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={filePath};Extended Properties=\"Excel 8.0;HDR=YES;\"";

            using (var connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                var query = "SELECT * FROM [Sheet1$]";
                using (var cmd = new OleDbCommand(query, connection))
                {
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var item = new NSLoadDef
                            {
                                //LoadCase = Convert.ToInt32(reader["LoadDef"]),
                                GravityProxy = Convert.ToDouble(reader["GravityProxy"]),
                                AdNonSeiCoefficient = Convert.ToDouble(reader["AdNonSeiCoefficient"]),
                                BenNonSeiCoefficient = Convert.ToDouble(reader["BenNonSeiCoefficient"]),
                                AdSeiCoefficient = Convert.ToDouble(reader["AdSeiCoefficient"]),
                                BenSeiCoefficient = Convert.ToDouble(reader["BenSeiCoefficient"]),
                                NonSesimicCoefficient = Convert.ToDouble(reader["NonSesimicCoefficient"]),
                                SesimicCoefficient = Convert.ToDouble(reader["SesimicCoefficient"]),
                                FreComCoefficient = Convert.ToDouble(reader["FreComCoefficient"]),
                                QuasiPreComCoefficient = Convert.ToDouble(reader["QuasiPreComCoefficient"])
                            };
                            data.Add(item);
                        }
                    }
                }
            }

            return data;
        }
        private void TESTVALUE()
        {
            /// ClientServiceProvider

            ProgressDisplayService progressDisplayService = ClientServiceProvider.ProgressDisplayService;
            CommandManager commandManager = ClientServiceProvider.CommandMgr;

            ClientTransactionManager clientTransactionManager = ClientServiceProvider.TransactionMgr;
            ViewHiliterManager viewHiliterManager = ClientServiceProvider.ViewHiliterMgr;

            GraphicViewManager graphicViewManager = ClientServiceProvider.GraphicViewMgr;
            int color = graphicViewManager.SelectSetColor; //控制 选中的颜色更改 
            graphicViewManager.SelectSetColor = 0000;
            float f = graphicViewManager.SelectSetWeight;
            ReadOnlyCollection<GraphicView> graphicViews = graphicViewManager.Views;

            ErrorHandler errorHandler = ClientServiceProvider.ErrHandler;
            CmnException cmnException = new CmnException("错误cmnException");
            errorHandler.LogError("", cmnException); //记录错误？
            //base.WriteStatusBarMsg("test 这是一条message");
            //errorHandler.ReportError(ErrorLevel.Critical, "", cmnException); //弹出错误窗口

            Preferences preferences = ClientServiceProvider.Preferences; //

            ValueManager valueManager = ClientServiceProvider.ValueMgr;
            //valueManager.GetDoubleValue("IJUAMJLoad");
            //valueManager.GetKeyName(0);

            WorkingSet workingSet = ClientServiceProvider.WorkingSet;
            int actConditionID = workingSet.ActiveConditionID;
            SP3DConnection connection = workingSet.ActiveConnection;
            SP3DConnections p3DConnections = workingSet.Connections;
            workingSet.Refresh(UpdateQuery.DefaultUpdate);
            Filter oFilter = new Filter();
            BOCollection businessObjects = workingSet.GetObjectsByFilter(oFilter, workingSet.ActiveConnection);  //新建一个Filter 可以获取ActiveConnection内的全部BO对象
            int bussinessCount = businessObjects.Count;

            /// MiddleServiceProvider

            UOMManager uOMManager = MiddleServiceProvider.UOMMgr;
            UnitName unitNameDistance = uOMManager.GetDefaultPrimaryUnit(UnitType.Distance);
            double c = uOMManager.ConvertUnitToUnit(UnitType.Distance, 1, unitNameDistance, UnitName.DISTANCE_MILLIMETER);

            UnitType[] unitTypes = uOMManager.GetAllUnitTypes();
            UnitName[] unitNames = uOMManager.GetAllUnitNamesForUnitType(UnitType.Distance);
            UOMFormat uOMFormatDistance = uOMManager.GetDefaultUnitFormat(UnitType.Distance);

            SiteManager siteManager = MiddleServiceProvider.SiteMgr;
            Site site = siteManager.ActiveSite;
            Location location = site.ActiveLocation;
            Plant plant = site.ActivePlant;
            ReadOnlyCollection<CatalogDatabaseInformation> catalogs = site.CatalogDatabaseInfos;

            TransactionManager transactionManager = MiddleServiceProvider.TransactionMgr;

            string strCurPath = Environment.GetEnvironmentVariable("PATH");
            string sExtraPath = Registry.GetValue(Registry.LocalMachine.ToString() +
                "\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\S3DHost.exe", "Path", "").ToString();
            if (string.IsNullOrEmpty(sExtraPath))
            {
                sExtraPath = Registry.GetValue(Registry.LocalMachine.ToString() +
    "\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\App Paths\\S3DHost.exe", "Path", "").ToString();
            }
            if (string.IsNullOrEmpty(sExtraPath))
            {
                Registry.GetValue(Registry.LocalMachine.ToString() +
    "\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\TaskHost.exe", "Path", "").ToString();
            }
            if (string.IsNullOrEmpty(sExtraPath))
            {
                Registry.GetValue(Registry.LocalMachine.ToString() +
    "\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\App Paths\\TaskHost.exe", "Path", "").ToString();
            }

            if (!string.IsNullOrEmpty(sExtraPath))
            {
                Environment.SetEnvironmentVariable("PATH", sExtraPath + ";" + strCurPath, EnvironmentVariableTarget.Process);
            }

        }


        private double m_unit_distance = 1;
        private double m_unit_force = 1;
        private double m_unit_moment = 1;
        private delegate void SetPos(int ipos, string vinfo);
    }
}
